<?php

class SJB_Miscellaneous_EmailScheduling extends SJB_Function
{
	public function execute()
	{
		set_time_limit(0);

		$notifiedEmails = array();
		$email_scheduling = SJB_Settings::getSettingByName('email_scheduling');
		$number_emails = SJB_Settings::getSettingByName('number_emails');
		$send_emails = SJB_Settings::getSettingByName('send_emails');
		$limit = $number_emails - $send_emails;
		$limit = ($limit > 0) ? $limit : 20;
		$letters = SJB_DB::query('SELECT * FROM `email_scheduling` ORDER BY `id` ASC LIMIT 0, ?n', $limit);

		if ($email_scheduling && $number_emails || count($letters)) {
			foreach ($letters as $letter) {
				$params = $letter;
				unset($params['id']);

				$email = new SJB_Email($params['email']);
				$email->setSubject($params['subject']);
				$email->setText($params['text']);
				$email->setFile($params['file']);
				if ($email->send(true)) {
					SJB_DB::query('DELETE FROM `email_scheduling` WHERE `id` = ?n', $letter['id']);
					array_push($notifiedEmails, $params['email']);
				}
			}
		}

		$template_processor = SJB_System::getTemplateProcessor();

		$template_processor->assign('notified_emails', $notifiedEmails);
		$scheduler_log = $template_processor->fetch('email_scheduler_log.tpl');

		if ($log_file = @fopen('email_scheduler.log', 'a+')) {
			fwrite($log_file, $scheduler_log);
			fclose($log_file);
		}
	}
}